package root.communication;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	private int port;
	private String address;
	
	public Client(String address, int port)
	{
		this.port = port;
		this.address = address;
		try
		{
			socket = new Socket(address, port);
			socket.setKeepAlive(true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
			MessageProcessor.in = in;
			String input = in.readLine();
			out.println(MessageProcessor.process(input));
		}
		catch(Exception e)
		{
			System.err.println("Unable to initialize connection");
		}
	}
	
	public int countClients()
	{
		try
		{
			out.println(MessageProcessor.countClientsQuery());
			String num = MessageProcessor.process(in.readLine());
			return Integer.parseInt(num);
		}
		catch (Exception e)
		{
			return 0;
		}
	}
	
	
	public void listClients()
	{
		try
		{
			String s = MessageProcessor.listClientsQuery();
			out.println(s);
			s=in.readLine();
			MessageProcessor.process(s);
		}
		catch (Exception e)
		{
			System.err.println("Error occured while querying for the list of clients: "+e);
		}
	}

	public void execute(String command)
	{	
		try
		{
			String s = MessageProcessor.executeCommand(command);
			out.println(s);
			s=in.readLine();
			s= MessageProcessor.process(s);
			if (s!=null)
				System.out.println(s);
		}
		catch (Exception e)
		{
			System.err.println("Error occured while processing 'exec' query: "+e);
		}
	}
	
	public void executeBash(String command)
	{	
		try
		{
			String s = MessageProcessor.executeBashCommand(command);
			out.println(s);
			s=in.readLine();
			s= MessageProcessor.process(s);
			if (s!=null)
				System.out.println(s);
		}
		catch (Exception e)
		{
			System.err.println("Error occured while processing 'exec' query: "+e);
		}
	}
	public void showLogs(int num)
	{
		try
		{
			out.println(MessageProcessor.globalLogsQuery(num));
			MessageProcessor.process(in.readLine());
		}
		catch (Exception e)
		{
			System.err.println("Retrieving logs failed");
		}
	}
}
